/**
 * 消息模型
 * Created by jinlei on 14-9-24.
 */
module.exports = {

  types:{
    description:function(value) {
      return true;
    }
  },

  attributes: {
    toUserNames: {
      type: 'array',
      required: true,
      description: '消息接受人的用户名，支持多个用户名'
    },
    fromUserName: {
      type: 'string',
      required: true,
      description: '消息发送人的用户名'
    },
    serviceName: {
      type: 'string',
      required: true,
      description: '消息服务名'
    },
    content: {
      type: 'json',
      required: true,
      description: '消息内容'
    },
    isHandle: {
      type: "boolean",
      required: true,
      defaultsTo: false,
      description: '是否需要消息接受人处理'
    }
  },

  beforeValidate: function (values, next) {
    if (_.has(values, 'serviceName')) {

      MessageService.findOne({name: values.serviceName})
        .exec(function (error, result) {
          if (error) return next(error);

          if (_.has(result, 'id')) {
            return next();
          } else {
            return next("It can not find this message service");
          }
        });
    } else {
      return next();
    }

  }

}